#include "venuedetaildialog.h"
#include "ui_venuedetaildialog.h"
#include "session.h"
#include "databasemanager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDate>
#include <QTime>
#include <QDebug>
#include <QHeaderView>
#include <QItemSelectionModel>
#include <QPainter>
#include <QPixmap>

VenueDetailDialog::VenueDetailDialog(const VenueDetail &venue, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::VenueDetailDialog),
    currentVenue(venue)
{
    ui->setupUi(this);
    this->setWindowTitle(venue.name + " 详情");

    // 显示场馆基本信息
    ui->venueNameLabel->setText("<b>" + venue.name + "</b>");
    ui->venueAddressLabel->setText("地址: " + venue.address);
    ui->venueHoursLabel->setText("开放时间: " + venue.opening_hours);
    ui->venueIntroLabel->setText("介绍: " + venue.introduction);
    ui->venueIntroLabel->setWordWrap(true);

    // 背景图通过 paintEvent 设置，其他控件设为半透明卡片样式
    QString cardStyle = R"(
        QWidget {
            background-color: rgba(255, 255, 255, 210);
            border-radius: 12px;
        }
    )";
    ui->widget->setStyleSheet(cardStyle);
    ui->widget_2->setStyleSheet(cardStyle);
    ui->activitiesTableView->setStyleSheet(cardStyle);

    // 标题样式
    ui->venueNameLabel->setStyleSheet(R"(
        QLabel {
            font-size: 22px;
            font-weight: bold;
            color: #2c3e50;
        }
    )");

    // 地址/时间/介绍样式
    QString labelStyle = R"(
        QLabel {
            font-size: 14px;
            color: #34495e;
        }
    )";
    ui->venueAddressLabel->setStyleSheet(labelStyle);
    ui->venueHoursLabel->setStyleSheet(labelStyle);
    ui->venueIntroLabel->setStyleSheet(labelStyle);

    // 活动表格美化
    ui->activitiesTableView->setAlternatingRowColors(true);
    ui->activitiesTableView->setStyleSheet(R"(
        QHeaderView::section {
            background-color: #3498db;
            color: white;
            padding: 4px;
            border: none;
        }
        QTableView {
            font-size: 13px;
            selection-background-color: #3498db;
            selection-color: white;
            alternate-background-color: #f5f5f5;
        }
    )");
    ui->activitiesTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->activitiesTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->activitiesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->activitiesTableView->setSelectionMode(QAbstractItemView::SingleSelection);

    // “预约”按钮样式
    ui->reserveActivityButton->setStyleSheet(R"(
        QPushButton {
            background-color: #f39c12;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 6px 20px;
            font-size: 16px;
        }
        QPushButton:hover {
            background-color: #f5b041;
        }
        QPushButton:pressed {
            background-color: #d68910;
        }
    )");

    // 加载活动
    activitiesModel = new QSqlQueryModel(this);
    ui->activitiesTableView->setModel(activitiesModel);
    loadActivities();
}

// 设置背景图填充整个窗口
void VenueDetailDialog::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap background("C:/Users/m1937/Pictures/Screenshots/bcv.png");
    painter.drawPixmap(this->rect(), background);  // 填满窗口
    QDialog::paintEvent(event);
}

VenueDetailDialog::~VenueDetailDialog()
{
    delete ui;
}

void VenueDetailDialog::loadActivities()
{
    if (!DatabaseManager::instance().getDatabase().isOpen()) {
        qDebug() << "数据库未打开，无法加载活动。";
        return;
    }

    QString queryStr = QString(
        "SELECT event_id, name, type, start_date, end_date "
        "FROM Exhibitions_Events "
        "WHERE venue_id = %1 ORDER BY start_date DESC;")
        .arg(currentVenue.venue_id);

    activitiesModel->setQuery(queryStr, DatabaseManager::instance().getDatabase());

    if (activitiesModel->lastError().isValid()) {
        qDebug() << "加载活动失败:" << activitiesModel->lastError().text();
    }
}

void VenueDetailDialog::on_reserveActivityButton_clicked()
{
    int visitorId = Session::getVisitorId();
    if (visitorId <= 0) {
        QMessageBox::critical(this, "错误", "未获取到有效的用户ID，无法预订！");
        return;
    }

    if (!DatabaseManager::instance().getDatabase().isOpen()) {
        QMessageBox::critical(this, "错误", "数据库未连接，无法预订！");
        return;
    }

    QItemSelectionModel *selection = ui->activitiesTableView->selectionModel();
    if (!selection->hasSelection()) {
        QMessageBox::warning(this, "预订失败", "请先选择一个活动！");
        return;
    }

    QModelIndex selectedIndex = selection->selectedRows().first();
    int eventId = activitiesModel->data(activitiesModel->index(selectedIndex.row(), 0)).toInt();

    QString visitDate = QDate::currentDate().toString("yyyy-MM-dd");
    QString visitTime = QTime::currentTime().toString("HH:mm:ss");

    QSqlQuery query(DatabaseManager::instance().getDatabase());
    query.prepare("INSERT INTO Venue_Visits (venue_id, event_id, visitor_id, visit_date, visit_time) "
                  "VALUES (:venue_id, :event_id, :visitor_id, :visit_date, :visit_time);");
    query.bindValue(":venue_id", currentVenue.venue_id);
    query.bindValue(":event_id", eventId);
    query.bindValue(":visitor_id", visitorId);
    query.bindValue(":visit_date", visitDate);
    query.bindValue(":visit_time", visitTime);

    if (query.exec()) {
        QMessageBox::information(this, "预订成功", "活动预订成功！");
    } else {
        QMessageBox::critical(this, "预订失败", "数据库错误：" + query.lastError().text());
        qDebug() << "预订失败:" << query.lastError().text();
    }
}
